package top.lingkang.finaloauth2.client.annotation;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import top.lingkang.finaloauth2.client.http.ResourceServerHolder;
import top.lingkang.finaloauth2.utils.CommonUtils;

import java.util.Set;

/**
 * @author lingkang
 * Created by 2022/4/3
 */
@Aspect
public class ImplOauth2CheckRole {

    @Autowired(required = false)
    private ResourceServerHolder resourceServerHolder;

    @Around("@within(top.lingkang.finaloauth2.client.annotation.Oauth2CheckRole) || @annotation(top.lingkang.finaloauth2.client.annotation.Oauth2CheckRole)")
    public Object impl(ProceedingJoinPoint joinPoint) throws Throwable {
        Set<String> has = resourceServerHolder.getRole();
        Oauth2CheckRole clazz = joinPoint.getTarget().getClass().getAnnotation(Oauth2CheckRole.class);
        if (clazz != null) {
            check(clazz, has);
        }
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Oauth2CheckRole method = signature.getMethod().getAnnotation(Oauth2CheckRole.class);
        if (method != null) {
            check(clazz, has);
        }
        return joinPoint.proceed();
    }

    private void check(Oauth2CheckRole check, Set<String> role) {
        if (check.anyRole().length != 0)
            CommonUtils.checkRole(check.anyRole(), role);
        if (check.allRole().length != 0)
            CommonUtils.checkAndRole(check.allRole(), role);
    }
}
